package com.genITeam.ria.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;

import com.genITeam.ria.exception.NGFException;
import com.genITeam.ria.utility.HibernateUtils;
import com.genITeam.ria.vo.Posts;
import com.genITeam.ria.vo.ResponseVo;

public class SearchForumDAO {

	public SearchForumDAO() {
		BasicConfigurator.configure();
	}

	Logger logger = Logger.getLogger(SearchForumDAO.class);

	/**
	 * searchForum Execute the query using hibernate and get all the Forum,
	 * Thread and Psot contain the matched Title and message and return in the
	 * response object
	 * 
	 * @param Posts ,
	 *            Session
	 * 
	 * @return ResponseVo
	 * @throws NGFException
	 */

	public ResponseVo searchForum(Posts posts, Session session)
			throws NGFException {

		ResponseVo responseVo = new ResponseVo();
		List searchResult = null;
		try {
			logger.info("Start searchForum");
			searchResult = session.createCriteria(Posts.class).add(
					Expression.like("title", "%" + posts.getTitle() + "%"))
					.add(
							Expression.like("message", "%" + posts.getMessage()
									+ "%")).addOrder(Order.desc("postDate"))
					.list();

			ArrayList searchForumResult = new ArrayList();
			searchForumResult.addAll(searchResult);
			responseVo.setSearchForumResult(searchForumResult);

		} catch (Exception e) {
			System.out.println(e.toString());
			logger.error(e.toString());
			throw new NGFException(e.getMessage());
		}
		return responseVo;
	}

	public static void main(String[] args) {
		Session session = null;
		Transaction tx = null;
		try {
			SearchForumDAO searchForumDAO = new SearchForumDAO();
			session = HibernateUtils.getSessionFactory().getCurrentSession();
			tx = session.getTransaction();
			tx.begin();
			Posts posts = new Posts();
			posts.setTitle("irfan");
			posts.setMessage("");
			searchForumDAO.searchForum(posts, session);
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			System.out.println("Exception " + e.getMessage());
		}

	}

}
